package com.example.kotlinExample.controller.advice

import com.example.kotlinExample.exception.ApiException
import com.example.kotlinExample.vo.ResultVO
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice


/**
 *
 *
 * @author liliang
 */
@RestControllerAdvice(basePackages = ["com.example.kotlinExample.controller"])
class ResponseControllerAdvice : ResponseBodyAdvice<Any?> {

    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>)
            = returnType.parameterType != ResultVO::class.java

    override fun beforeBodyWrite(data: Any?, returnType: MethodParameter, selectedContentType: MediaType,
                                 selectedConverterType: Class<out HttpMessageConverter<*>>,
                                 request: ServerHttpRequest, response: ServerHttpResponse): Any? {
        if (returnType.genericParameterType == String::class.java) {
            val objectMapper = ObjectMapper()
            return try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                objectMapper.writeValueAsString(ResultVO(data))
            } catch (e: JsonProcessingException) {
                throw ApiException("返回String类型错误")
            }
        }
        // 将原本的数据包装在ResultVO里
        return ResultVO(data)
    }

}